using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;

namespace SimpleFramework
{
    public class BinaryFileLoader : TemplateLoader<byte[]>
    {
        public readonly static SimplePool<BinaryFileLoader> POOL = new SimplePool<BinaryFileLoader>();

        protected override void OnStart()
        {
            if (FileSetting.IsDebug)
                Debug.Log("Load File: " + m_Url);
            m_Request = UnityWebRequest.Get(m_Url);
            m_Request.SendWebRequest();
        }

        protected override bool OnUpdate()
        {
            this.onProgress.Invoke(this, m_Request.downloadProgress);
            return m_Request.isDone;
        }

        protected override void OnFinish()
        {
            if (m_Request.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.LogErrorFormat("[LoadFile] URL:{0} Error:{1}", m_Url, m_Request.error);
                if (m_TryCount > 0)
                {
                    m_TryCount--;
                    m_Request = null;
                    Reset();
                }
                else
                {
                    this.onFailure.Invoke(this, m_Request.error);
                    m_Request = null;
                    POOL.UnSpawn(this);
                }
            }
            else
            {
                DownloadHandler handler = m_Request.downloadHandler;
                if (string.IsNullOrEmpty(handler.text) && (handler.data == null || handler.data.Length == 0))
                {
                    Debug.LogErrorFormat("[LoadFile] URL:{0} Error:{1}", m_Url, m_Request.error);
                    this.onFailure.Invoke(this, m_Request.error);
                }
                else
                {
                    this.onComplete.Invoke(this, handler.data);
                }
                m_Request = null;
                POOL.UnSpawn(this);
            }
        }
    }
}